<?php 
/**
 * 题目一：递增数组，找到两个数字的和为S
 * 		解答:首位指针，指针指向的两个数的和大于S，尾指针后移，小于S，头指针前移
 * 题目二：和为S的连续正数序列
 * 		解答：大小指针，小指针指向1，大指针指向2，求和，如果和大于S，小指针加1，小于S，大指针加1
 */

function FindContinuousSequence1($array, $sum)
{
	if (!$array || (!is_array($array))) {
		exit('数据输入有误');
	}
    $count = count($array);
    $firstIndex = 0;
    $endIndex = $count - 1;
    $flat = false;
    while ($firstIndex < $endIndex) {
    	$tempSum = $array[$firstIndex] + $array[$endIndex];
    	if ($tempSum == $sum) {
    		var_dump($array[$firstIndex], $array[$endIndex]);
    		$flat = true;
    		break;
    	} elseif ($tempSum < $sum) {
    		$firstIndex++;
    	} else {
    		$endIndex--;
    	}
    }

    if (!$flat) {
    	exit('数据输入有误');
    }
}


/*$arr = [1,2,3,5,6,8,9];
FindContinuousSequence1($arr, 8);*/


function FindContinuousSequence2($sum)
{
	if ($sum < 3) {
		return;
	}
	$small = 1;
	$large = 2;
	$middle = intval((1 + $sum) / 2);
	$curSum = $small + $large;
	while ($small < $middle) {
		if ($curSum == $sum) {
			printList($small, $large);
		}
		while ($small < $middle && ($curSum > $sum)) {
			$curSum -= $small;
			$small++;
			if ($curSum == $sum) {
				printList($small, $large);
			}
		}
		$large++;
		$curSum += $large;
	}
}

function printList($small, $large) 
{
	for ($i=$small; $i <= $large ; $i++) { 
		echo " ".$i;
	}
	echo "<br />";
}

FindContinuousSequence2(15);

